<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库状态" prop="rkZt">
        <el-select size="mini" v-model="queryParams.rkZt" placeholder="请选择入库状态" clearable>
          <el-option
            v-for="dict in dict.type.sbrk_rkzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库方式" prop="rkFs">
        <el-select size="mini" v-model="queryParams.rkFs" placeholder="请选择入库方式" clearable>
          <el-option
            v-for="dict in dict.type.sbrk_rkfs"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库日期">
        <el-date-picker size="mini"
                        v-model="daterangeRkRq"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="入库人" prop="rkR">
        <el-input size="mini"
                  v-model="queryParams.rkR"
                  placeholder="请输入入库人"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sbrk:sbrk:add']"
        >新增入库单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sbrk:sbrk:edit']"
        >修改入库单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sbrk:sbrk:remove']"
        >删除入库单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sbrk:sbrk:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['sbrk:sbrk:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="sbrkList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="入库状态" align="center" prop="rkZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sbrk_rkzt" :value="scope.row.rkZt"/>
        </template>
      </el-table-column>
      <el-table-column label="入库方式" align="center" prop="rkFs">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sbrk_rkfs" :value="scope.row.rkFs"/>
        </template>
      </el-table-column>
      <el-table-column label="入库日期" align="center" prop="rkRq" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rkRq, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库人" align="center" prop="rkR"/>
      <el-table-column label="入库详情" align="center" >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleButtonClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sbrk:sbrk:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sbrk:sbrk:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 导入对话框 -->
    <vxe-modal :title="upload.title" v-model="upload.open" width="400px" showFooter show-zoom resize>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 添加或修改设备入库对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="入库方式" prop="rkFs">
                <el-select v-model="form.rkFs" placeholder="请选择入库方式">
                  <el-option
                    v-for="dict in dict.type.sbrk_rkfs"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入库日期" prop="rkRq">
                <el-date-picker clearable style="width: 100%;"
                                v-model="form.rkRq"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择入库日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入库人" prop="rkR">
                <el-input v-model="form.rkR" placeholder="请输入入库人"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">设备入库明细</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSbglSbrkRkmx">添加设备</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSbglSbrkRkmx">移除
              </el-button>
            </el-col>
          </el-row>
          <el-table height="45vh" :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    :data="sbglSbrkRkmxList" :row-class-name="rowSbglSbrkRkmxIndex"
                    @selection-change="handleSbglSbrkRkmxSelectionChange" ref="sbglSbrkRkmx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column align="center" label="设备名称" prop="sbName" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="单位" prop="dw" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="规格型号" prop="ggXh" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="所在项目" prop="szXm" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="出厂编号" prop="ccBh" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="自编号" prop="zBh" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="固定资产编号" prop="gdZcBh" width="150" show-overflow-tooltip/>
            <el-table-column align="center" label="备注" prop="bz" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input v-model="scope.row.bz" placeholder="请输入备注"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 设备多选组件 -->
    <SbDuoX ref="sbDuoX"/>

    <!-- 设备入库详情 -->
    <SbRkXq ref="sbRkXq"/>
  </div>
</template>

<script>
import {addSbrk, delSbrk, getSbrk, getSbrkId, listSbrk, updateSbrk} from "@/api/sbrk/sbrk";
import {getToken} from "@/utils/auth";
import SbDuoX from "@/views/components/sbDuoX/index.vue";
import SbRkXq from "@/views/sbgl/sbrk/components/SbRkXq.vue";

export default {
  name: "Sbrk",
  components: {SbRkXq, SbDuoX},
  dicts: ['sbgl_sbdw', 'sbrk_rkzt', 'sbrk_rkfs'],
  provide() {
    return {
      updateSbLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.sbglSbrkRkmxList.some(existingItem => existingItem.ccBh === item.ccBh);
          if (!exists) {
            this.sbglSbrkRkmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      selectedRow: null, // 保存当前选中的行
      getSbrkId: null, //从后端获取到的设备入库ID (UUID)
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSbglSbrkRkmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备入库表格数据
      sbrkList: [],
      // 设备入库入库明细表格数据
      sbglSbrkRkmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeRkRq: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rkZt: null,
        rkFs: null,
        rkRq: null,
        rkR: null,
        userId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rkFs: [{required: true, message: "入库方式不能为空", trigger: "change"}],
        rkRq: [{required: true, message: "入库日期不能为空", trigger: "blur"}],
        rkR: [{required: true, message: "入库人不能为空", trigger: "blur"}],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sbrk/sbrk/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查询设备入库详情
    handleButtonClick(row) {
      this.$refs.sbRkXq.handleOpen(row)
    },
    /** 自定义编号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 查询设备入库列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRkRq && '' != this.daterangeRkRq) {
        this.queryParams.params["beginRkRq"] = this.daterangeRkRq[0];
        this.queryParams.params["endRkRq"] = this.daterangeRkRq[1];
      }
      listSbrk(this.queryParams).then(response => {
        this.sbrkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sbrkId: this.getSbrkId,
        rkZt: null,
        rkFs: null,
        rkRq: null,
        rkR: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.sbglSbrkRkmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRkRq = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sbrkId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      getSbrkId().then(res => {
        this.getSbrkId = res.msg
        this.reset();
      })
      this.reset();
      this.open = true;
      this.title = "添加设备入库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const sbrkId = row.sbrkId || this.ids
      getSbrk(sbrkId).then(response => {
        this.form = response.data;
        this.sbglSbrkRkmxList = response.data.sbglSbrkRkmxList;
        this.open = true;
        this.title = "修改设备入库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.sbglSbrkRkmxList = this.sbglSbrkRkmxList;
          if (this.form.idWhere != null) {
            updateSbrk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // console.log(this.form.sbglSbrkRkmxList.length, 'asddsaasdadws')
            addSbrk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sbrkIds = row.sbrkId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delSbrk(sbrkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 设备入库入库明细序号 */
    rowSbglSbrkRkmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 设备入库入库明细添加按钮操作 */
    handleAddSbglSbrkRkmx() {
      this.$refs.sbDuoX.handleOpen(this.sbglSbrkRkmxList)
      // let obj = {};
      // obj.sbName = "";
      // obj.dw = "";
      // obj.ggXh = "";
      // obj.szXm = "";
      // obj.ccBh = "";
      // obj.zBh = "";
      // obj.gdZcBh = "";
      // obj.bz = "";
      // this.sbglSbrkRkmxList.push(obj);
    },
    /** 设备入库入库明细删除按钮操作 */
    handleDeleteSbglSbrkRkmx() {
      if (this.checkedSbglSbrkRkmx.length == 0) {
        this.$modal.msgError("请先选择要删除的设备入库入库明细数据");
      } else {
        const sbglSbrkRkmxList = this.sbglSbrkRkmxList;
        const checkedSbglSbrkRkmx = this.checkedSbglSbrkRkmx;
        this.sbglSbrkRkmxList = sbglSbrkRkmxList.filter(function (item) {
          return checkedSbglSbrkRkmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSbglSbrkRkmxSelectionChange(selection) {
      this.checkedSbglSbrkRkmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sbrk/sbrk/export', {
        ...this.queryParams
      }, `sbrk_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('sbrk/sbrk/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备入库导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
